package com.hua.demo.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hua.demo.edu.entity.Subject;
import com.hua.demo.edu.entity.excel.SubjectData;
import com.hua.demo.edu.service.SubjectService;
import com.hua.exceptionhandler.GuliException;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
//因为subjectexcelllistenner不能交给spring管理，
    public SubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new GuliException(20001,"文件上数据为空");
        }
        Subject existonesubject = this.existonesubject(subjectService, subjectData.getOneSubjectName());
        if(existonesubject==null){//没有相同的一级分类，可以进行添加
            existonesubject=new Subject();
            existonesubject.setParentId("0");
            existonesubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existonesubject);
        }
        String pid =existonesubject.getId();
        Subject existtwosubject = this.existtwosubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if(existtwosubject==null){//没有相同的一级分类，可以进行添加
            existtwosubject=new Subject();
            existtwosubject.setParentId(pid);
            existtwosubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existtwosubject);
        }


        //判断一级分类不可以重复添加
    }
    private Subject existonesubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> wrapper=new QueryWrapper<>();

        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Subject one = subjectService.getOne(wrapper);
        return one;
    }
    private Subject existtwosubject(SubjectService subjectService, String twoSubjectName, String pid){
        QueryWrapper<Subject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",twoSubjectName);
        wrapper.eq("parent_id",pid);
        Subject two = subjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}